from django.db import transaction
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response

from rest_framework.viewsets import ModelViewSet

from cards.api.serializers import CardSerializer, CustomerCardSerializer
from cards.models import Card, CustomerCard
from finance.api.utils import update_account


class CardListAPIView(ListAPIView):
    """优惠卡列表"""
    permission_classes = ()
    queryset = Card.objects.exclude(status=1)
    serializer_class = CardSerializer
    pagination_class = None


class CardViewSet(ModelViewSet):
    """优惠卡"""
    permission_classes = ()
    queryset = Card.objects.all()
    serializer_class = CardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(code__contains=name))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class CustomerCardViewSet(ModelViewSet):
    """客户优惠卡"""
    permission_classes = ()
    queryset = CustomerCard.objects.all()
    serializer_class = CustomerCardSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name")
        status = self.request.query_params.get("status")
        search_date = self.request.query_params.getlist("search_date[]", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        if status:
            queryset = queryset.filter(status=int(status))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(receipt_time__date__range=(search_date[0], search_date[1]))

        return queryset

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                # 减少账号金额
                if instance.sale_class == 1:
                    update_account(instance.account_id, instance.actual_money)

                self.perform_destroy(instance)

            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.update_accounts(select_ids)
        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)

    def update_accounts(self, select_ids):
        objs = self.serializer_class.Meta.model.objects.filter(id__in=select_ids)
        for obj in objs:
            # 减少账号金额
            if obj.sale_class == 1:
                update_account(obj.account_id, obj.actual_money)

